﻿namespace GBALib.Sound
{
    public delegate void PullAudio(short[] buffer, int length);

    public class GBASoundPlayer : IDisposable
    {
        private int samplesPerUpdate;
        private AutoResetEvent[] fillEvent = new AutoResetEvent[2];
        private Thread thread;
        private PullAudio pullAudio;
        private short channels;
        private bool halted;
        private bool running;

        public GBASoundPlayer(/*Control owner, */PullAudio pullAudio, short channels)
        {
            this.channels = channels;
            this.pullAudio = pullAudio;

            this.samplesPerUpdate = 512;

            fillEvent[0] = new AutoResetEvent(false);
            fillEvent[1] = new AutoResetEvent(false);

            this.Pause();
            this.running = true;

            this.thread.Start();
        }

        public void Pause()
        {
            if (this.halted) return;

            this.halted = true;

            if (null != this.thread)
            {
                Monitor.Enter(this.thread);
            }
        }

        public void Resume()
        {
            if (!this.halted) return;

            this.halted = false;

            if (null != this.thread)
            {
                Monitor.Pulse(this.thread);
                Monitor.Exit(this.thread);
            }
        }

        private void SoundPlayback()
        {
            if (null == this.thread)
            {
                return;
            }

            lock (this.thread)
            {
                if (!this.running) return;

                // Set up the initial sound buffer to be the full length
                int bufferLength = this.samplesPerUpdate * 2 * this.channels;
                short[] soundData = new short[bufferLength];

                // Prime it with the first x seconds of data
                this.pullAudio(soundData, soundData.Length);
            }
        }


        public void Dispose()
        {
            this.running = false;
            this.Resume();
        }
    }
}
